
/*
 *  Copyright (c) 2015. For Intelligent Group.
 *
 */

package com.intelligent.ispc.client.core.controller;

import com.google.common.collect.Lists;
import com.intelligent.ispc.client.core.validator.SysGrrDto;
import com.intelligent.ispc.client.core.validator.SysSpcCcwDto;
import com.intelligent.ispc.client.core.validator.SysSpcCpwDto;
import com.intelligent.ispc.client.core.validator.SysSpcDto;
import com.intelligent.ispc.client.core.view.configuration.AnalysisConfigPanel;
import com.intelligent.ispc.client.event.ThrowExceptionEvent;
import com.intelligent.ispc.client.utils.ApplicationBeanUtils;
import com.intelligent.ispc.client.utils.EventBusUtils;
import com.intelligent.ispc.client.utils.SystemConfigUtils;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.constant.AppConstant;
import com.intelligent.ispc.core.dto.GrrConfigDto;
import com.intelligent.ispc.core.dto.SpcConfigDto;
import com.intelligent.ispc.core.service.SystemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by Lucien.Chen on 2016/8/25.
 */
@Component
public class SystemController {
    @Autowired
    private SystemService systemService;

    /**
     * @return grr config data
     */
    public SysGrrDto findGrrConfig() {
        GrrConfigDto grrConfigDto;
        SysGrrDto sysGrrDto = new SysGrrDto();
        try {
            grrConfigDto = systemService.findGrrConfig();
            BeanUtils.copyProperties(grrConfigDto, sysGrrDto);
            String[] modelValues;
            String modelValue = grrConfigDto.getModelValue();
            modelValues = subString(modelValue, 1, modelValue.length() - 1);
            sysGrrDto.setParts(modelValues[0].trim());
            sysGrrDto.setAppraisers(modelValues[1].trim());
            sysGrrDto.setTrails(modelValues[2].trim());

            String[] ruleValues;
            String rule = grrConfigDto.getRule();
            ruleValues = subString(rule, 1, rule.length() - 1);
            sysGrrDto.setExcellent(ruleValues[0].trim());
            sysGrrDto.setAdequate(ruleValues[1].trim());
            sysGrrDto.setMarginal(ruleValues[2].trim());
            sysGrrDto.setDigit(String.valueOf(grrConfigDto.getDigit()));
            return sysGrrDto;
        } catch (ApplicationException e) {
            EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
        return null;
    }

    /**
     * @return spc config data
     */
    public SysSpcDto findSpcConfig() {
        List<SpcConfigDto> spcConfigs;
        SysSpcDto sysSpcDto = new SysSpcDto();
        List<SysSpcCpwDto> sysSpcCpwDtos = Lists.newArrayList();
        List<SysSpcCcwDto> sysSpcCcwDtos = Lists.newArrayList();
        try {
            spcConfigs = systemService.findSpcConfigs();

            SpcConfigDto spcgroup = spcConfigs.get(0);
            sysSpcDto.setId(spcgroup.getId());
            if (spcgroup.getSpcNdGroup() != null) {
                sysSpcDto.setNdGroupKey(true);
                sysSpcDto.setSpcNdGroupKey(spcgroup.getSpcNdGroup().toString());
            }
            if (spcgroup.getSpcCcGroup() != null) {
                sysSpcDto.setCcGroupKey(true);
                sysSpcDto.setSpcCcGroupKey(spcgroup.getSpcCcGroup().toString());
            }

            for (int i = 1; i < spcConfigs.size(); i++) {
                SpcConfigDto spcConfigDto = spcConfigs.get(i);
                String value = spcConfigDto.getValue();
                String[] values = subString(value, 0, value.length());
                if (spcConfigDto.getConfigType().equals("CPW")) {
                    SysSpcCpwDto sysSpcCpwDto = new SysSpcCpwDto();
                    BeanUtils.copyProperties(spcConfigDto, sysSpcCpwDto);
                    if (!value.isEmpty()) {
                        int index = 0;
                        sysSpcCpwDto.setValue1(values[index].trim());
                        index++;
                        sysSpcCpwDto.setValue2(values[index].trim());
                        index++;
                        sysSpcCpwDto.setValue3(values[index].trim());
                        index++;
                        sysSpcCpwDto.setValue4(values[index].trim());
                        index++;
                    }
                    sysSpcCpwDtos.add(sysSpcCpwDto);
                } else if (spcConfigDto.getConfigType().equals("CCW")) {
                    SysSpcCcwDto sysSpcCcwDto = new SysSpcCcwDto();
                    BeanUtils.copyProperties(spcConfigDto, sysSpcCcwDto);
                    if (!value.isEmpty()) {
                        int index = 0;
                        sysSpcCcwDto.setValue1(values[index].trim());
                        index++;
                        sysSpcCcwDto.setValue2(values[index].trim());
                        index++;
                        sysSpcCcwDto.setValue3(values[index].trim());
                        index++;
                        if (values[index].trim().equals("1")) {
                            sysSpcCcwDto.setAnalyse(true);
                        } else {
                            sysSpcCcwDto.setAnalyse(false);
                        }
                    }
                    sysSpcCcwDtos.add(sysSpcCcwDto);
                } else if (spcConfigDto.getConfigType().equals("DIGIT")) {
                    sysSpcDto.setDigitId(spcConfigDto.getId());
                    sysSpcDto.setDigit(spcConfigDto.getValue());
                }
            }
            sysSpcDto.setSysSpcCpwDtos(sysSpcCpwDtos);
            sysSpcDto.setSysSpcCcwDtos(sysSpcCcwDtos);
            return sysSpcDto;
        } catch (ApplicationException e) {
            EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
        return null;
    }

    /**
     * @return grr group keys
     */
    public List<String> getGrrKeys() {
        List<String> grrKeys;
        try {
            grrKeys = systemService.getGrrKeys();
            return grrKeys;
        } catch (ApplicationException e) {
            EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
        return null;
    }

    /**
     * sysGrrDto changed into grrConfigDto, then save grr config
     *
     * @param sysGrrDto grr config data
     */
    public void saveGrrConfig(SysGrrDto sysGrrDto) {
        GrrConfigDto grrConfigDto = new GrrConfigDto();
        try {
            BeanUtils.copyProperties(sysGrrDto, grrConfigDto);
            String modelValue = "[" + sysGrrDto.getParts() + "," + sysGrrDto.getAppraisers() + "," + sysGrrDto.getTrails() + "]";
            grrConfigDto.setModelValue(modelValue);
            String rule = "[" + sysGrrDto.getExcellent() + "," + sysGrrDto.getAdequate() + "," + sysGrrDto.getMarginal() + "]";
            grrConfigDto.setRule(rule);
            Integer digit = Integer.valueOf(sysGrrDto.getDigit());
            grrConfigDto.setDigit(digit);
            systemService.createOrUpdateGrrConfig(grrConfigDto);
            SystemConfigUtils.getInstance().setGrrDigit(digit);

            ApplicationBeanUtils.getBean(AnalysisConfigPanel.class).grrSaveSuccess();
        } catch (ApplicationException e) {
            EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
            ApplicationBeanUtils.getBean(AnalysisConfigPanel.class).grrSaveFail();
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
    }

    /**
     * sysSpcDto changed into spcConfigDto, then save spc config
     *
     * @param sysSpcDto spc config data
     */
    public void saveSpcConfig(SysSpcDto sysSpcDto) {
        List<SpcConfigDto> spcConfigs = Lists.newArrayList();
        List<SysSpcCpwDto> sysSpcCpwDtos = sysSpcDto.getSysSpcCpwDtos();
        List<SysSpcCcwDto> sysSpcCcwDtos = sysSpcDto.getSysSpcCcwDtos();
        try {
            SpcConfigDto spcGroup = new SpcConfigDto();
            spcGroup.setId(sysSpcDto.getId());
            if (sysSpcDto.isNdGroupKey()) {
                spcGroup.setSpcNdGroup(Integer.valueOf(sysSpcDto.getSpcNdGroupKey()));
            }
            if (sysSpcDto.isCcGroupKey()) {
                spcGroup.setSpcCcGroup(Integer.valueOf(sysSpcDto.getSpcCcGroupKey()));
            }
            spcConfigs.add(spcGroup);

            for (int i = 0; i < sysSpcCpwDtos.size(); i++) {
                SpcConfigDto spcConfigDto = new SpcConfigDto();
                SysSpcCpwDto sysSpcCpwDto = sysSpcCpwDtos.get(i);
                BeanUtils.copyProperties(sysSpcCpwDto, spcConfigDto);
                String value = sysSpcCpwDto.getValue1() + "," + sysSpcCpwDto.getValue2() + "," + sysSpcCpwDto.getValue3() + "," + sysSpcCpwDto.getValue4();

                spcConfigDto.setValue(value);
                spcConfigs.add(spcConfigDto);
            }

            for (int i = 0; i < sysSpcCcwDtos.size(); i++) {
                SpcConfigDto spcConfigDto = new SpcConfigDto();
                SysSpcCcwDto sysSpcCcwDto = sysSpcCcwDtos.get(i);
                BeanUtils.copyProperties(sysSpcCcwDto, spcConfigDto);
                String value = sysSpcCcwDto.getValue1() + "," + sysSpcCcwDto.getValue2() + "," + sysSpcCcwDto.getValue3() + ",";
                if (sysSpcCcwDto.getAnalyse()) {
                    value = value + "1";
                } else {
                    value = value + "0";
                }
                spcConfigDto.setValue(value);
                spcConfigs.add(spcConfigDto);
            }

            SpcConfigDto digitSpcConfigDto = new SpcConfigDto();
            digitSpcConfigDto.setId(sysSpcDto.getDigitId());
            digitSpcConfigDto.setConfigType(AppConstant.SPC_CONFIG_DIGIT);
            digitSpcConfigDto.setName(AppConstant.SPC_CONFIG_DIGIT);
            digitSpcConfigDto.setValue(sysSpcDto.getDigit());
            spcConfigs.add(digitSpcConfigDto);
            systemService.updateMultiSpcConfig(spcConfigs);
            SystemConfigUtils.getInstance().setSpcDigit(Integer.valueOf(sysSpcDto.getDigit()));

            ApplicationBeanUtils.getBean(AnalysisConfigPanel.class).spcSaveSuccess();
        } catch (ApplicationException e) {
            ApplicationBeanUtils.getBean(AnalysisConfigPanel.class).spcSaveFail();
            EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
    }

    /*
     *sub string form beginIndex to endIndex
     */
    private String[] subString(String value, int beginIndex, int endIndex) {
        String[] values;
        if (value.length() > 1) {
            values = value.substring(beginIndex, endIndex).split(",");
        } else {
            values = null;
        }
        return values;
    }
}
